'use strict';
const fs = require("fs");
const iconv  = require("iconv-lite");
const https = require("https");

module.exports = {
    json,
    isEmpty,
    format,
    containEmpty,
    readFile,
    writeFile,
    radomImgs,
    getAddress
};

//json格式化数据模板
function json(msg, status = 1, data) {
    return {
        status,
        msg: msg instanceof Error ? msg.message : msg,
        data
    };
}


//判断是否为undefined | null | ""
function isEmpty(e) {
    return e === undefined || e === null || e === "";
}


//判断对象是否包含空，只判断第一层
function containEmpty(e) {
    if (typeof e == 'object') {
        return Object.values(e).includes(undefined);
    }
    return true
}


//时间戳转格式化时间
//type 为1就只拼接年月日 默认精确到秒
function format(timestamp, type) {
    if (isEmpty(timestamp)) return "";
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = fillZero(date.getMonth() + 1);
    const day = fillZero(date.getDate());

    if (type === 1) {
        return `${year}-${month}-${day}`;
    }
    const h = fillZero(date.getHours());
    const m = fillZero(date.getMinutes());
    const s = fillZero(date.getSeconds());

    function fillZero(e) {
        return e < 10 ? "0" + e : e;
    }

    return `${year}-${month}-${day} ${h}:${m}:${s}`;
}


// 文件读取封装
function readFile(path){
    return new Promise((resovle,reject)=>{
        fs.readFile(path,(err,data)=>{
            if(err){
                reject(err);
            }else{
                resovle(data);
            }
        })
    })
}


// 文件写入封装
function writeFile(path,data){
    console.log("write:",path,data);
    return new Promise((resovle,reject)=>{
        fs.writeFile(path,data,err=>{
            if(err){
                reject(err);
            }else{
                resovle();
            }
        })
    })
}

// 随机网络图片
function radomImgs(){
    let imgs = [
        "https://www.cemcode.com/imgs/image1.png",
        "https://www.cemcode.com/imgs/image2.png",
        "https://www.cemcode.com/imgs/image3.png",
        "https://www.cemcode.com/imgs/image4.png",
    ]
    return imgs[Math.floor(Math.random()*imgs.length)];
}

// 获取IP的大概地址
function getAddress(ip){
    return new Promise((resolve,reject)=>{
        https.get(`https://whois.pconline.com.cn/ip.jsp?ip=${ip}`, function (res) {
            let datas = []
            let size = 0
            res.on("data", function (data) {
                datas.push(data)
                size += data.length
            })
            res.on("end", function () {
                let buff = Buffer.concat(datas, size)
                let address = iconv.decode(buff, "gbk").trim()
                if(address.length>100){
                    address = "获取失败";
                }
                resolve(address);
            })
        }).on("error", function (err) {
            reject(err)
        })
    })
}